{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Make sure you already run\n",
    "\n",
    "1. [bert-preprocessing.ipynb](bert-preprocessing.ipynb)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '2'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "from tensor2tensor.utils import beam_search"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pickle\n",
    "\n",
    "with open('train-test-bert.pkl', 'rb') as fopen:\n",
    "    dataset = pickle.load(fopen)\n",
    "    \n",
    "train_X = dataset['train_X']\n",
    "train_Y = dataset['train_Y']\n",
    "test_X = dataset['test_X']\n",
    "test_Y = dataset['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "GO = 101\n",
    "PAD = 0\n",
    "EOS = 102"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/optimization.py:87: The name tf.train.Optimizer is deprecated. Please use tf.compat.v1.train.Optimizer instead.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "import bert\n",
    "from bert import run_classifier\n",
    "from bert import optimization\n",
    "from bert import tokenization\n",
    "from bert import modeling"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "BERT_VOCAB = 'multi_cased_L-12_H-768_A-12/vocab.txt'\n",
    "BERT_INIT_CHKPNT = 'multi_cased_L-12_H-768_A-12/bert_model.ckpt'\n",
    "BERT_CONFIG = 'multi_cased_L-12_H-768_A-12/bert_config.json'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/tokenization.py:125: The name tf.gfile.GFile is deprecated. Please use tf.io.gfile.GFile instead.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "tokenizer = tokenization.FullTokenizer(\n",
    "      vocab_file=BERT_VOCAB, do_lower_case=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_vocab = len(tokenizer.vocab)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "bert_config = modeling.BertConfig.from_json_file(BERT_CONFIG)\n",
    "\n",
    "epoch = 20\n",
    "batch_size = 32\n",
    "warmup_proportion = 0.1\n",
    "num_train_steps = int(len(train_X) / batch_size * epoch)\n",
    "num_warmup_steps = int(num_train_steps * warmup_proportion)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "def ln(inputs, epsilon = 1e-8, scope=\"ln\"):\n",
    "    with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n",
    "        inputs_shape = inputs.get_shape()\n",
    "        params_shape = inputs_shape[-1:]\n",
    "    \n",
    "        mean, variance = tf.nn.moments(inputs, [-1], keep_dims=True)\n",
    "        beta= tf.get_variable(\"beta\", params_shape, initializer=tf.zeros_initializer())\n",
    "        gamma = tf.get_variable(\"gamma\", params_shape, initializer=tf.ones_initializer())\n",
    "        normalized = (inputs - mean) / ( (variance + epsilon) ** (.5) )\n",
    "        outputs = gamma * normalized + beta\n",
    "        \n",
    "    return outputs\n",
    "\n",
    "def scaled_dot_product_attention(Q, K, V,\n",
    "                                 causality=False, dropout_rate=0.,\n",
    "                                 training=True,\n",
    "                                 scope=\"scaled_dot_product_attention\"):\n",
    "    with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n",
    "        d_k = Q.get_shape().as_list()[-1]\n",
    "\n",
    "        outputs = tf.matmul(Q, tf.transpose(K, [0, 2, 1]))  # (N, T_q, T_k)\n",
    "        outputs /= d_k ** 0.5\n",
    "        outputs = mask(outputs, Q, K, type=\"key\")\n",
    "        if causality:\n",
    "            outputs = mask(outputs, type=\"future\")\n",
    "        outputs = tf.nn.softmax(outputs)\n",
    "        attention = tf.transpose(outputs, [0, 2, 1])\n",
    "        #tf.summary.image(\"attention\", tf.expand_dims(attention[:1], -1))\n",
    "        outputs = mask(outputs, Q, K, type=\"query\")\n",
    "        outputs = tf.layers.dropout(outputs, rate=dropout_rate, training=training)\n",
    "        outputs = tf.matmul(outputs, V)\n",
    "    return outputs\n",
    "\n",
    "def mask(inputs, queries=None, keys=None, type=None):\n",
    "    padding_num = -2 ** 32 + 1\n",
    "    if type in (\"k\", \"key\", \"keys\"):\n",
    "        masks = tf.sign(tf.reduce_sum(tf.abs(keys), axis=-1))  # (N, T_k)\n",
    "        masks = tf.expand_dims(masks, 1) # (N, 1, T_k)\n",
    "        masks = tf.tile(masks, [1, tf.shape(queries)[1], 1])  # (N, T_q, T_k)\n",
    "        paddings = tf.ones_like(inputs) * padding_num\n",
    "        outputs = tf.where(tf.equal(masks, 0), paddings, inputs)  # (N, T_q, T_k)\n",
    "    elif type in (\"q\", \"query\", \"queries\"):\n",
    "        masks = tf.sign(tf.reduce_sum(tf.abs(queries), axis=-1))  # (N, T_q)\n",
    "        masks = tf.expand_dims(masks, -1)  # (N, T_q, 1)\n",
    "        masks = tf.tile(masks, [1, 1, tf.shape(keys)[1]])  # (N, T_q, T_k)\n",
    "        outputs = inputs*masks\n",
    "    elif type in (\"f\", \"future\", \"right\"):\n",
    "        diag_vals = tf.ones_like(inputs[0, :, :])  # (T_q, T_k)\n",
    "        tril = tf.linalg.LinearOperatorLowerTriangular(diag_vals).to_dense()  # (T_q, T_k)\n",
    "        masks = tf.tile(tf.expand_dims(tril, 0), [tf.shape(inputs)[0], 1, 1])  # (N, T_q, T_k)\n",
    "        paddings = tf.ones_like(masks) * padding_num\n",
    "        outputs = tf.where(tf.equal(masks, 0), paddings, inputs)\n",
    "    else:\n",
    "        print(\"Check if you entered type correctly!\")\n",
    "\n",
    "\n",
    "    return outputs\n",
    "\n",
    "def multihead_attention(queries, keys, values,\n",
    "                        num_heads=8, \n",
    "                        dropout_rate=0,\n",
    "                        training=True,\n",
    "                        causality=False,\n",
    "                        scope=\"multihead_attention\"):\n",
    "    d_model = queries.get_shape().as_list()[-1]\n",
    "    with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n",
    "        # Linear projections\n",
    "        Q = tf.layers.dense(queries, d_model, use_bias=False) # (N, T_q, d_model)\n",
    "        K = tf.layers.dense(keys, d_model, use_bias=False) # (N, T_k, d_model)\n",
    "        V = tf.layers.dense(values, d_model, use_bias=False) # (N, T_k, d_model)\n",
    "        \n",
    "        Q_ = tf.concat(tf.split(Q, num_heads, axis=2), axis=0) # (h*N, T_q, d_model/h)\n",
    "        K_ = tf.concat(tf.split(K, num_heads, axis=2), axis=0) # (h*N, T_k, d_model/h)\n",
    "        V_ = tf.concat(tf.split(V, num_heads, axis=2), axis=0) # (h*N, T_k, d_model/h)\n",
    "\n",
    "        outputs = scaled_dot_product_attention(Q_, K_, V_, causality, dropout_rate, training)\n",
    "        outputs = tf.concat(tf.split(outputs, num_heads, axis=0), axis=2 ) # (N, T_q, d_model)\n",
    "        outputs += queries\n",
    "        outputs = ln(outputs)\n",
    " \n",
    "    return outputs\n",
    "\n",
    "def ff(inputs, num_units, scope=\"positionwise_feedforward\"):\n",
    "    with tf.variable_scope(scope, reuse=tf.AUTO_REUSE):\n",
    "        outputs = tf.layers.dense(inputs, num_units[0], activation=tf.nn.relu)\n",
    "        outputs = tf.layers.dense(outputs, num_units[1])\n",
    "        outputs += inputs\n",
    "        outputs = ln(outputs)\n",
    "    \n",
    "    return outputs\n",
    "\n",
    "def label_smoothing(inputs, epsilon=0.1):\n",
    "    V = inputs.get_shape().as_list()[-1] # number of channels\n",
    "    return ((1-epsilon) * inputs) + (epsilon / V)\n",
    "\n",
    "def sinusoidal_position_encoding(inputs, mask, repr_dim):\n",
    "    T = tf.shape(inputs)[1]\n",
    "    pos = tf.reshape(tf.range(0.0, tf.to_float(T), dtype=tf.float32), [-1, 1])\n",
    "    i = np.arange(0, repr_dim, 2, np.float32)\n",
    "    denom = np.reshape(np.power(10000.0, i / repr_dim), [1, -1])\n",
    "    enc = tf.expand_dims(tf.concat([tf.sin(pos / denom), tf.cos(pos / denom)], 1), 0)\n",
    "    return tf.tile(enc, [tf.shape(inputs)[0], 1, 1]) * tf.expand_dims(tf.to_float(mask), -1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, learning_rate,\n",
    "                num_blocks = 4, num_heads = 8, ratio_hidden = 2, beam_width = 5):\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype=tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype=tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        \n",
    "        def forward(x, y, reuse = False):\n",
    "            \n",
    "            with tf.variable_scope('bert',reuse=reuse):\n",
    "                model = modeling.BertModel(\n",
    "                    config=bert_config,\n",
    "                    is_training=False,\n",
    "                    input_ids=x,\n",
    "                    use_one_hot_embeddings=False)\n",
    "                embedding = model.get_embedding_table()\n",
    "                memory = model.get_sequence_output()\n",
    "            \n",
    "            decoder_embedded = tf.nn.embedding_lookup(embedding, y)\n",
    "            de_masks = tf.sign(y)\n",
    "            decoder_embedded += sinusoidal_position_encoding(y, de_masks, size_layer)\n",
    "            dec = decoder_embedded\n",
    "            \n",
    "            for i in range(num_blocks):\n",
    "                with tf.variable_scope('decoder_self_attn_%d'%i,reuse=reuse):\n",
    "                    dec = multihead_attention(queries=dec,\n",
    "                                              keys=dec,\n",
    "                                              values=dec,\n",
    "                                              num_heads=num_heads,\n",
    "                                              causality=True,\n",
    "                                              scope=\"self_attention\")\n",
    "\n",
    "                    dec = multihead_attention(queries=dec,\n",
    "                                              keys=memory,\n",
    "                                              values=memory,\n",
    "                                              num_heads=num_heads,\n",
    "                                              causality=False,\n",
    "                                              scope=\"vanilla_attention\")\n",
    "                    \n",
    "                    dec = ff(dec, num_units=[size_layer * ratio_hidden, size_layer])\n",
    "                \n",
    "            weights = tf.transpose(embedding)\n",
    "            logits = tf.einsum('ntd,dk->ntk', dec, weights)\n",
    "            return logits\n",
    "        \n",
    "        main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        self.training_logits = forward(self.X, decoder_input)\n",
    "\n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = optimization.create_optimizer(self.cost, learning_rate, \n",
    "                                                       num_train_steps, num_warmup_steps, False)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n",
    "        \n",
    "        initial_ids = tf.fill([batch_size], GO)\n",
    "        \n",
    "        def symbols_to_logits(ids):\n",
    "            x = tf.contrib.seq2seq.tile_batch(self.X, beam_width)\n",
    "            logits = forward(x, ids, reuse = True)\n",
    "            return logits[:, tf.shape(ids)[1]-1, :]\n",
    "        \n",
    "        final_ids, final_probs, _ = beam_search.beam_search(\n",
    "            symbols_to_logits,\n",
    "            initial_ids,\n",
    "            beam_width,\n",
    "            tf.reduce_max(self.X_seq_len),\n",
    "            size_vocab,\n",
    "            0.0,\n",
    "            eos_id = EOS)\n",
    "        \n",
    "        self.predicting_ids = final_ids"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 768\n",
    "learning_rate = 1e-5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/modeling.py:171: The name tf.variable_scope is deprecated. Please use tf.compat.v1.variable_scope instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/modeling.py:409: The name tf.get_variable is deprecated. Please use tf.compat.v1.get_variable instead.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/modeling.py:490: The name tf.assert_less_equal is deprecated. Please use tf.compat.v1.assert_less_equal instead.\n",
      "\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/bert/modeling.py:671: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use keras.layers.dense instead.\n",
      "WARNING:tensorflow:From <ipython-input-10-0623a9ea865e>:102: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/init_ops.py:1251: calling VarianceScaling.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From <ipython-input-10-0623a9ea865e>:45: add_dispatch_support.<locals>.wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:From <ipython-input-10-0623a9ea865e>:34: dropout (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use keras.layers.dropout instead.\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "import collections\n",
    "import re\n",
    "\n",
    "def get_assignment_map_from_checkpoint(tvars, init_checkpoint):\n",
    "    \"\"\"Compute the union of the current variables and checkpoint variables.\"\"\"\n",
    "    assignment_map = {}\n",
    "    initialized_variable_names = {}\n",
    "\n",
    "    name_to_variable = collections.OrderedDict()\n",
    "    for var in tvars:\n",
    "        name = var.name\n",
    "        m = re.match('^(.*):\\\\d+$', name)\n",
    "        if m is not None:\n",
    "            name = m.group(1)\n",
    "        name_to_variable[name] = var\n",
    "\n",
    "    init_vars = tf.train.list_variables(init_checkpoint)\n",
    "\n",
    "    assignment_map = collections.OrderedDict()\n",
    "    for x in init_vars:\n",
    "        (name, var) = (x[0], x[1])\n",
    "        if 'bert/' + name not in name_to_variable:\n",
    "            continue\n",
    "        assignment_map[name] = name_to_variable['bert/' + name]\n",
    "        initialized_variable_names[name] = 1\n",
    "        initialized_variable_names[name + ':0'] = 1\n",
    "\n",
    "    return (assignment_map, initialized_variable_names)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "tvars = tf.trainable_variables()\n",
    "\n",
    "checkpoint = BERT_INIT_CHKPNT\n",
    "assignment_map, initialized_variable_names = get_assignment_map_from_checkpoint(tvars, \n",
    "                                                                                checkpoint)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/training/saver.py:1276: checkpoint_exists (from tensorflow.python.training.checkpoint_management) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use standard file APIs to check for files with this prefix.\n",
      "INFO:tensorflow:Restoring parameters from multi_cased_L-12_H-768_A-12/bert_model.ckpt\n"
     ]
    }
   ],
   "source": [
    "saver = tf.train.Saver(var_list = assignment_map)\n",
    "saver.restore(sess, checkpoint)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(1, 5, 13)"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sess.run(model.predicting_ids, feed_dict = {model.X: [train_X[0]]}).shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [],
   "source": [
    "def pad_sentence_batch(sentence_batch, pad_int):\n",
    "    padded_seqs = []\n",
    "    seq_lens = []\n",
    "    max_sentence_len = max([len(sentence) for sentence in sentence_batch])\n",
    "    for sentence in sentence_batch:\n",
    "        padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n",
    "        seq_lens.append(len(sentence))\n",
    "    return padded_seqs, seq_lens"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4167/4167 [36:02<00:00,  1.93it/s, accuracy=0.0694, cost=6.54]\n",
      "minibatch loop: 100%|██████████| 89/89 [00:16<00:00,  5.42it/s, accuracy=0.178, cost=4.76] \n",
      "minibatch loop:   0%|          | 0/4167 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 5.470412, training avg acc 0.112731\n",
      "epoch 1, testing avg loss 4.825023, testing avg acc 0.160569\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4167/4167 [35:59<00:00,  1.93it/s, accuracy=0.13, cost=5.97]  \n",
      "minibatch loop: 100%|██████████| 89/89 [00:15<00:00,  5.61it/s, accuracy=0.279, cost=4.13]\n",
      "minibatch loop:   0%|          | 0/4167 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 4.331696, training avg acc 0.214640\n",
      "epoch 2, testing avg loss 4.143205, testing avg acc 0.239354\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4167/4167 [35:59<00:00,  1.93it/s, accuracy=0.185, cost=5.37]\n",
      "minibatch loop: 100%|██████████| 89/89 [00:15<00:00,  5.64it/s, accuracy=0.346, cost=3.57]\n",
      "minibatch loop:   0%|          | 0/4167 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 3.624350, training avg acc 0.318347\n",
      "epoch 3, testing avg loss 3.634863, testing avg acc 0.318458\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4167/4167 [35:57<00:00,  1.93it/s, accuracy=0.227, cost=4.79]\n",
      "minibatch loop: 100%|██████████| 89/89 [00:15<00:00,  5.57it/s, accuracy=0.37, cost=3.2]  \n",
      "minibatch loop:   0%|          | 0/4167 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 3.167339, training avg acc 0.390191\n",
      "epoch 4, testing avg loss 3.300180, testing avg acc 0.373873\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4167/4167 [35:49<00:00,  1.94it/s, accuracy=0.287, cost=4.33]\n",
      "minibatch loop: 100%|██████████| 89/89 [00:16<00:00,  5.54it/s, accuracy=0.409, cost=3.06]\n",
      "minibatch loop:   0%|          | 0/4167 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 2.842982, training avg acc 0.441878\n",
      "epoch 5, testing avg loss 3.147791, testing avg acc 0.399979\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4167/4167 [35:49<00:00,  1.94it/s, accuracy=0.31, cost=3.86] \n",
      "minibatch loop: 100%|██████████| 89/89 [00:16<00:00,  5.55it/s, accuracy=0.428, cost=2.99]\n",
      "minibatch loop:   0%|          | 0/4167 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 2.586160, training avg acc 0.483048\n",
      "epoch 6, testing avg loss 3.126966, testing avg acc 0.405724\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4167/4167 [35:49<00:00,  1.94it/s, accuracy=0.375, cost=3.52]\n",
      "minibatch loop: 100%|██████████| 89/89 [00:16<00:00,  5.52it/s, accuracy=0.438, cost=2.85]\n",
      "minibatch loop:   0%|          | 0/4167 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 2.372910, training avg acc 0.518034\n",
      "epoch 7, testing avg loss 3.052107, testing avg acc 0.422895\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4167/4167 [35:49<00:00,  1.94it/s, accuracy=0.403, cost=3.29]\n",
      "minibatch loop: 100%|██████████| 89/89 [00:15<00:00,  5.57it/s, accuracy=0.452, cost=2.69]\n",
      "minibatch loop:   0%|          | 0/4167 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 2.200384, training avg acc 0.545937\n",
      "epoch 8, testing avg loss 2.927400, testing avg acc 0.441286\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4167/4167 [35:49<00:00,  1.94it/s, accuracy=0.417, cost=3.04] \n",
      "minibatch loop: 100%|██████████| 89/89 [00:15<00:00,  5.58it/s, accuracy=0.481, cost=2.61]\n",
      "minibatch loop:   0%|          | 0/4167 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 2.073574, training avg acc 0.566716\n",
      "epoch 9, testing avg loss 2.864531, testing avg acc 0.455790\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4167/4167 [35:49<00:00,  1.94it/s, accuracy=0.486, cost=2.69] \n",
      "minibatch loop: 100%|██████████| 89/89 [00:16<00:00,  5.53it/s, accuracy=0.49, cost=2.59] \n",
      "minibatch loop:   0%|          | 0/4167 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 1.947256, training avg acc 0.588113\n",
      "epoch 10, testing avg loss 2.861142, testing avg acc 0.458657\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4167/4167 [35:48<00:00,  1.94it/s, accuracy=0.532, cost=2.34] \n",
      "minibatch loop: 100%|██████████| 89/89 [00:16<00:00,  5.56it/s, accuracy=0.466, cost=2.72]\n",
      "minibatch loop:   0%|          | 0/4167 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 1.798666, training avg acc 0.614890\n",
      "epoch 11, testing avg loss 2.964870, testing avg acc 0.448801\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4167/4167 [35:49<00:00,  1.94it/s, accuracy=0.546, cost=2.15] \n",
      "minibatch loop: 100%|██████████| 89/89 [00:16<00:00,  5.55it/s, accuracy=0.452, cost=2.9] \n",
      "minibatch loop:   0%|          | 0/4167 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 1.656793, training avg acc 0.640974\n",
      "epoch 12, testing avg loss 3.111073, testing avg acc 0.434066\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4167/4167 [35:49<00:00,  1.94it/s, accuracy=0.565, cost=1.98] \n",
      "minibatch loop: 100%|██████████| 89/89 [00:16<00:00,  5.55it/s, accuracy=0.433, cost=2.98]\n",
      "minibatch loop:   0%|          | 0/4167 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 1.533094, training avg acc 0.663895\n",
      "epoch 13, testing avg loss 3.217668, testing avg acc 0.423850\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4167/4167 [35:49<00:00,  1.94it/s, accuracy=0.606, cost=1.93] \n",
      "minibatch loop: 100%|██████████| 89/89 [00:16<00:00,  5.54it/s, accuracy=0.423, cost=2.92]\n",
      "minibatch loop:   0%|          | 0/4167 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 1.419215, training avg acc 0.685455\n",
      "epoch 14, testing avg loss 3.227339, testing avg acc 0.426352\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4167/4167 [35:49<00:00,  1.94it/s, accuracy=0.657, cost=1.78] \n",
      "minibatch loop: 100%|██████████| 89/89 [00:16<00:00,  5.53it/s, accuracy=0.447, cost=2.88]\n",
      "minibatch loop:   0%|          | 0/4167 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 1.309490, training avg acc 0.706482\n",
      "epoch 15, testing avg loss 3.232316, testing avg acc 0.430102\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4167/4167 [35:48<00:00,  1.94it/s, accuracy=0.667, cost=1.6]  \n",
      "minibatch loop: 100%|██████████| 89/89 [00:15<00:00,  5.57it/s, accuracy=0.433, cost=2.87]\n",
      "minibatch loop:   0%|          | 0/4167 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 1.203308, training avg acc 0.727816\n",
      "epoch 16, testing avg loss 3.250415, testing avg acc 0.434590\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4167/4167 [35:48<00:00,  1.94it/s, accuracy=0.699, cost=1.34] \n",
      "minibatch loop: 100%|██████████| 89/89 [00:15<00:00,  5.56it/s, accuracy=0.452, cost=2.82]\n",
      "minibatch loop:   0%|          | 0/4167 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 1.095675, training avg acc 0.750086\n",
      "epoch 17, testing avg loss 3.245824, testing avg acc 0.445811\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4167/4167 [35:54<00:00,  1.93it/s, accuracy=0.792, cost=1.16] \n",
      "minibatch loop: 100%|██████████| 89/89 [00:15<00:00,  5.59it/s, accuracy=0.481, cost=2.93]\n",
      "minibatch loop:   0%|          | 0/4167 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 0.993417, training avg acc 0.772005\n",
      "epoch 18, testing avg loss 3.277383, testing avg acc 0.451739\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4167/4167 [35:52<00:00,  1.94it/s, accuracy=0.778, cost=1.1]  \n",
      "minibatch loop: 100%|██████████| 89/89 [00:15<00:00,  5.67it/s, accuracy=0.486, cost=2.93]\n",
      "minibatch loop:   0%|          | 0/4167 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 0.892157, training avg acc 0.794355\n",
      "epoch 19, testing avg loss 3.342973, testing avg acc 0.450040\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 4167/4167 [35:54<00:00,  1.93it/s, accuracy=0.745, cost=1.13] \n",
      "minibatch loop: 100%|██████████| 89/89 [00:15<00:00,  5.64it/s, accuracy=0.438, cost=2.93]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 0.804806, training avg acc 0.813287\n",
      "epoch 20, testing avg loss 3.441328, testing avg acc 0.446938\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        maxlen = max([len(s) for s in train_X[i : index] + train_Y[i : index]])\n",
    "        batch_x, seq_x = pad_sentence_batch(train_X[i : index], PAD)\n",
    "        batch_y, seq_y = pad_sentence_batch(train_Y[i : index], PAD)\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x, seq_x = pad_sentence_batch(test_X[i : index], PAD)\n",
    "        batch_y, seq_y = pad_sentence_batch(test_Y[i : index], PAD)\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(20, 5, 94)"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "test_size = 20\n",
    "\n",
    "batch_x, _ = pad_sentence_batch(test_X[: test_size], PAD)\n",
    "feed = {model.X: batch_x}\n",
    "logits = sess.run(model.predicting_ids, feed_dict = feed)\n",
    "logits.shape"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
